package com.letv.so.servlet;

import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;

import com.alibaba.fastjson.JSONObject;
import com.letv.so.bean.VideoBean;
import com.letv.so.constants.DownPlatFormEnum;
import com.letv.so.constants.PayPlatFormEnum;
import com.letv.so.service.QueryDataService;
import com.letv.so.util.NumberUtil;
import com.letv.so.util.SpecialFieldUtil;
import com.letv.so.util.StringUtil;
import com.letv.so.util.ThreadLocalUtil;
import com.letv.so.util.XMLUtil;
import com.letv.so.util.ZHConverter;

/**
 * 
 */
public abstract class AbstractQueryDataServlet extends BaseServlet {

    private static final long serialVersionUID = -4530700506509711878L;
    private Logger logger = org.slf4j.LoggerFactory.getLogger(AbstractQueryDataServlet.class);
    protected static final String SIMPLE = "s";
    protected static final String LE_ID_MAP_PERFIX = "leid_";
    protected static final List<String> TRADITIONAL = Arrays
            .asList(new String[] { "zh_hk", "zh_tw" });
    protected QueryDataService queryDataService;
    protected ZHConverter converter = null;
    protected Map<String, Map<String,List<String>>> rtnkeys = new HashMap<String, Map<String,List<String>>>();

    public void init() throws ServletException {
        super.init();
        queryDataService = (QueryDataService) wac.getBean("queryDataService");
        converter = ZHConverter.getInstance();
        String webPah = this.getServletContext().getRealPath("/");
        String configPath = Paths.get(webPah, "WEB-INF", "classes", "config.xml").toString();
        XMLUtil.parserXml(new File(configPath),rtnkeys);
    }

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        long beginTime = System.currentTimeMillis();
        String rawInfo = request.getRequestURI() + "?"
                + request.getQueryString();
        // logger.debug("detail req{" + rawInfo + "},ts=" + beginTime);
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=UTF-8");
        Map<String, Object> ruleMap = new HashMap<String, Object>();
        Map<String, String> paras = new HashMap<String, String>();
        ThreadLocalUtil.setParasMap(paras);
        String soKey = request.getParameter("sk");// 关键词
        String op = request.getParameter("op");// 关键词
        int pn = NumberUtil.getInt(request.getParameter("pn"), 0);// 第几页
        int ps = NumberUtil.getInt(request.getParameter("ps"), 50);// 每页多少个
        String subsrc = request.getParameter("subsrc");
        String src = request.getParameter("src");
        String vrsAid = request.getParameter("vrsAid");
        String sid = request.getParameter("uniqueId");
        String lang = request.getParameter("lang");
        ThreadLocalUtil.calculatePlatform(request.getParameter("from"));
        ThreadLocalUtil.setCityInfo(request.getParameter("city_info"));
        ruleMap.put("lid", request.getParameter("lid"));
        ruleMap.put("pcp", request.getParameter("pcp"));
        ruleMap.put("website_id_list", request.getParameter("website_id_list"));
        ruleMap.put("soKey", soKey);
        ruleMap.put("op", op);
        ruleMap.put("pn", pn);
        ruleMap.put("ps", ps);
        ruleMap.put("subsrc", subsrc);
        ruleMap.put("src", src);
        ruleMap.put("vrsAid", vrsAid);
        ruleMap.put("letvOriginalId", request.getParameter("letvOriginalId"));
        if (StringUtils.isBlank(sid)) {
            sid = String.valueOf(System.currentTimeMillis());
        }
        if (StringUtils.isBlank(lang)) {
        	ThreadLocalUtil.setLang(SIMPLE);
        } else {
        	ThreadLocalUtil.setLang(lang.toLowerCase());
        }
        ruleMap.put("sid", sid);

        int videoListSize = NumberUtil.getInt(request.getParameter("vls"), 0);// 专辑关联的视频数量
        ruleMap.put("videoListSize", videoListSize);

        String result = query(ruleMap);

        String callback = request.getParameter("callback");// 回调
        if (!StringUtil.isBlank(callback)) {
            result = callback + "(" + result + ")";
        }

        long markTime = System.currentTimeMillis();
        logger.warn(sid + " GET " + rawInfo + " cost time|"
                + (markTime - beginTime));
        print(request, response, result);
    }

    public void print(HttpServletRequest request, HttpServletResponse response,
            String result) throws ServletException, IOException {
        String encode = request.getParameter("encode");
        encode = StringUtils.isBlank(encode) ? "UTF-8" : encode;
        response.setCharacterEncoding(encode);
        response.setContentType("text/javascript; charset=" + encode);
        this.printNoCache(response, result);
    }

    protected abstract String query(Map<String, Object> rule);


    protected void setPayAndDownFlag(VideoBean videoBean) {
        String ph = ThreadLocalUtil.getPh();
        if (StringUtils.isNotBlank(ph)) {
            String payPlatform = videoBean.getPayPlatform();
            String isPay = "0";
            String allowdown = "0";
            if (StringUtils.isNotBlank(payPlatform)) {
                isPay = calcIsPay(payPlatform,ph);
            }
            if ( StringUtils.isNotEmpty(isPay)) {
                videoBean.setIsPay(isPay);
            }
/*            String downloadPlatform = videoBean.getDownloadPlatform();
            if (StringUtils.isNotBlank(downloadPlatform)) {
                allowdown = calcDownload(downloadPlatform,ph);
            }
            if ( StringUtils.isNotEmpty(allowdown)) {
                videoBean.setAllowDownload(allowdown);
            }
            videoBean.setDownloadPlatform(null);*/
        }
//        videoBean.setPayPlatform(null);
    }
    
    private String calcDownload(String downloadPlatform,String ph) {
         DownPlatFormEnum downEnum = DownPlatFormEnum.valueOf(ph);
         if (downEnum != null) {
              if (downloadPlatform.indexOf(downEnum.getValue()) > 0) {
                  return "1";
              }else {
                  return "0";
              }
         }
        return null;
    }

    private String calcIsPay(String payPlatform,String ph) {
            PayPlatFormEnum payEnum = PayPlatFormEnum.valueOf(ph);
            if (payEnum != null) {
                if (payPlatform.indexOf(payEnum.getValue()) >= 0) {
                    return "1";
                } else {
                    return "0";
                }
            }
        return null;
    }

    protected void setPayAndDownFlag(JSONObject videoInfo) {
        String ph = ThreadLocalUtil.getPh();
        if (StringUtils.isNotBlank(ph)) {
            String payPlatform = videoInfo.getString("payPlatform");
            String isPay = "0";
            String allowdown = "0";
            if (StringUtils.isNotBlank(payPlatform)) {
                isPay = calcIsPay(payPlatform,ph);
            }
            //videoInfo.put("payPlatform", null);
            if ( StringUtils.isNotEmpty(isPay)) {
                videoInfo.put("isPay", isPay);
            }
/*            String downloadPlatform = videoInfo.getString("downloadPlatform");
            if (StringUtils.isNotBlank(downloadPlatform)) {
                allowdown = calcDownload(downloadPlatform,ph);
            }
            //videoInfo.put("downloadPlatform", null);
            if ( StringUtils.isNotEmpty(allowdown)) {
                videoInfo.put("allowDownload", allowdown);
            }*/
        }
    }
    protected String getRemoveStr(int rmN) {
        return ";"+rmN+";";
    }
    protected int removeOneVideo(String aid, List<VideoBean> videos) {
        int rmN = getRemoveNumber(aid);
        if (rmN  > 0 ) {
            logger.warn("WebSite rmN="+rmN);
            String rmIndex = ""+rmN;
            Iterator<VideoBean> it = videos.iterator();
            while(it.hasNext()) {
                String key = it.next().getAorder();
                if (rmIndex.equals(key)) {
                    it.remove();
                    break;
                } 
            }
        }
        return rmN;
    }
    
    private int getRemoveNumber(String eaid) {
        String from = ThreadLocalUtil.getFrom();
        Map<String,List<String>> map = rtnkeys.get(SpecialFieldUtil.WEBSITE_REMOVE);
        List<String> retainList = map.get(SpecialFieldUtil.WEBSITE_REMOVE_RETAIN);
        if (retainList != null && retainList.size() > 0){
            if (retainList.contains(from)) {
                return 0;
            } else {
                List<String> removeList = map.get(SpecialFieldUtil.WEBSITE_REMOVE_YES);
                if ( removeList !=null && removeList.size() >0) {
                    for (int i=0;i<removeList.size();i++) {
                        String remove = removeList.get(i);
                        if (StringUtils.isNotBlank(remove)&&remove.indexOf("'"+eaid+"'") >= 0 ) {
                            String[] rtn = remove.split("-");
                            if(rtn.length == 2) {
                                return Integer.valueOf(rtn[1]);
                            }
                        }
                    }
                }
            }
        }
        return 0;
    }
}
